 
/*
 * @Author: ZhouNan
 * @Date: 2022-04-16 18:10:05
 * @LastEditors: ZhouNan
 * @LastEditTime: 2022-04-21 20:02:02
 * @FilePath: \export_ts\src\core\01_ExtractAssetInfo.ts
 * @Description: 提取AssetInfo
 */

import { readJsonSync } from "fs-extra";
import { AssetInfo } from "../../@types/packages/asset-db/@types/public";
import { EXPORT_CONFIG_PATH } from "../const";
import Export from './02_Export';

let export_flag = '';

/** 使用快捷键走这儿 根据选中的导出 */
async function start() {
    let config = readJsonSync(EXPORT_CONFIG_PATH);
    if (!config) {
        console.warn('[Export-TS] not find export config');
        return;
    }
    export_flag = config.export_flag;
    let assetInfoArr = await getSelectList();
    assetInfoArr.forEach(info => {
        _exportSingleAsset(info);
    })
}

function exportSingleAsset(assetInfo: AssetInfo) {
    let config = readJsonSync(EXPORT_CONFIG_PATH);
    if (!config) {
        console.warn('[Export-TS] not find export config');
        return;
    }
    export_flag = config.export_flag;
    _exportSingleAsset(assetInfo);
}

/** 导出单个资源脚本 */
function _exportSingleAsset(assetInfo: AssetInfo) {
    let nodeTree = convertToNodeTree(assetInfo);
    Export.start(nodeTree, assetInfo);
}

/** 获取所有用户选中的资源信息 目前只处理 prefab 和 scene */
async function getSelectList() {
    let selectedAll = Editor.Selection.getSelected('asset');
    let assetInfoArr = [];
    for (let i = 0; i < selectedAll.length; i++) {
        let uuid = selectedAll[i];
        let assetInfo = await Editor.Message.request('asset-db', 'query-asset-info', uuid);
        if (assetInfo?.type == 'cc.Prefab' || assetInfo?.type == 'cc.SceneAsset') {
            assetInfoArr.push(assetInfo);
        }
    }
    return assetInfoArr;
}

function convertToNodeTree(assetInfo: AssetInfo) {
    let fileData = readJsonSync(assetInfo.file);
    let nodeTree = deepDealNodeInfo(fileData[1], null!, fileData);
    return nodeTree;
}

function deepDealNodeInfo(info: any, parentInfo: NodeTreeStruct, originData: any[]): NodeTreeStruct {
    let node: NodeTreeStruct = {
        name: info._name || '',
        parent: null!,
        children: [],
        components: [],
        isExport: false,
        childExportCount: 0
    }
    if (parentInfo) {
        node.parent = parentInfo;
    }
    if (node.name.startsWith(export_flag)) {
        node.isExport = true;
        if (node.parent) {
            node.parent.childExportCount++;
        }
        
        // deepAddParentCount(node);
    }
    if (Array.isArray(info._components)) {
        for (let i = 0; i < info._components.length; i++) {
            let o = info._components[i];
            let idx = o.__id__;
            let componentInfo = originData[idx];
            let name = componentInfo.__type__;
            node.components.push(name);
        }
    }
    if (Array.isArray(info._children)) {
        for (let i = 0; i < info._children.length; i++) {
            let o = info._children[i];
            let idx = o.__id__;
            let childInfo = originData[idx];
            let child = deepDealNodeInfo(childInfo, node, originData);
            node.children.push(child);
        }
    }
    return node;
}

function deepAddParentCount(node: NodeTreeStruct) {
    let parent = node.parent
    if (parent) {
        parent.childExportCount++;
        deepAddParentCount(parent);
    }
}

export default {
    start,
    exportSingleAsset,
}

export type NodeTreeStruct = {
    name: string,
    // 父节点
    parent: NodeTreeStruct,
    // 子节点
    children: NodeTreeStruct[],
    // 组件
    components: string[],
    // 默认0 ，子节点导出时也会使父节点+1；
    childExportCount: number,
    // 是否作为成员变量导出
    isExport: boolean,
}